package com.mnsq.subject.service.impl;

import com.mnsq.common.bean.condition.CommonBaseCondition;
import com.mnsq.common.bean.entity.CommonEntity;
import com.mnsq.common.bean.enums.StatusEnum;
import com.mnsq.common.dao.BaseDao;
import com.mnsq.common.tools.jpa.JpaExample;
import com.mnsq.common.tools.tool.BeanCopyUtils;
import com.mnsq.common.tools.tool.UUIDUtils;
import com.mnsq.subject.service.OperateService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @author 周俭
 */
@Log4j2
@Service
public class OperateServiceImpl<T extends CommonEntity, C extends CommonBaseCondition> implements OperateService<T, C> {
    @Autowired
    private BaseDao<T> baseDao;

    @Override
    public boolean done(T t, C c) {
        try {
            Optional<T> opt = baseDao.findOne(JpaExample.getInstance().getExample(c, c.getInstance()));
            if (opt.isPresent()) {
                T obj = opt.get();
                if (!StatusEnum.STATUS_VALID.value.equals(obj.getStatus())) {
                    BeanCopyUtils.copyNullProperties(t, obj);
                    obj.setStatus(StatusEnum.STATUS_VALID.value);
                    obj.setUpdateTime(new Date());
                    baseDao.saveAndFlush(obj);
                }
            } else {
                t.createInit();
                t.setUnique(UUIDUtils.getUnique());
                t.setUpdateTime(new Date());
                t.setCreateTime(new Date());
                baseDao.saveAndFlush(t);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return true;
    }

    @Override
    public boolean undone(T t, C c) {
        Optional<T> opt = baseDao.findOne(JpaExample.getInstance().getExample(c, c.getInstance()));
        if (opt.isPresent()) {
            T obj = opt.get();
            if (!StatusEnum.STATUS_DEL.value.equals(obj.getStatus())) {
                obj.setStatus(StatusEnum.STATUS_DEL.value);
                obj.setUpdateTime(new Date());
                baseDao.saveAndFlush(obj);
            }
        } else {
            t.createInit();
            t.setUnique(UUIDUtils.getUnique());
            t.setStatus(StatusEnum.STATUS_DEL.value);
            t.setCreateTime(new Date());
            t.setUpdateTime(new Date());
            baseDao.saveAndFlush(t);
        }
        return true;
    }
}
